const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const check = require('../../utils/check.js');
const app = getApp();

const rules = {
    company: '公司名称',
    dutyParagraph: '税号',
    mobile: '电话',
    address: '地址',
    openBank: '开户行',
    bankAccount: '账号',
    content: '发票内容',
    reason: '开票事由',
    reasonNote: '备注',
    postName: '姓名',
    postNumber: '手机',
    postAddress: '地址',
}
Page({
    data: {
        company: "",
        dutyParagraph: '',
        mobile: "",
        address: "",
        bankAccount: "",
        type: "0",
        openBank: '',
        id: '',
        result: [],
        // phoneError2: '',
        contents: ['注册费', '资料费', '咨询费', '展台费', '会务费'],
        showPicker: false,
        content: '',//发票内容
        index: '',//发票内容的下标
        matter: "",//开票事由
        reasons: ['海事论坛', '科技评价', '委托项目', '展台费', '其他'],//开票事由
        reasonMap: {},
        reason: "",//开票事由
        reasonNote: '',//开票事由，选择了‘其他’选项的备注
        remarks: '',
        // remarksError: '',//报错信息
        postAddress: "",
        postName: '',
        postNumber: '',

        // 错误提示
        companyError: '',
        dutyParagraphError: '',
        phoneError: '',
        addressError: '',
        openBankError: '',
        bankAccountError: '',
        contentError: '',
        reasonError: '',
        reasonNoteError: '',
        postNameError: '',
        postNumberError: '',
        postAddressError: '',

    },
    //电话校验格式
    phoneCheck2(e) {
        let results = check.isValidPhone(e.detail)
        this.setData({
            postNumberError: results
        })
    },
    phoneCheck(e) {
        let results = check.isValidPhone(e.detail)
        this.setData({
            mobileError: results
        })
    },
    showPicker() {
        this.setData({
            showPicker: true,
        })
    },
    onConfirm(e) {
        this.setData({
            content: e.detail.value,
            index: e.detail.index,
            showPicker: false,
            contentError: ''
        })
    },
    onCancel() {
        this.setData({
            showPicker: false,
        })
    },
    showPicker_2() {
        this.setData({
            showPicker2: true,
        })
    },
    onConfirm_2(e) {
        const reasonDesc = e.detail.value
        this.setData({
            matter: reasonDesc,
            reason: this.data.reasonMap[reasonDesc],
            showPicker2: false,
            reasonNote: '',
            reasonError: ''
        })
    },
    onCancel_2() {
        this.setData({
            showPicker2: false,
        })
    },
    onShareAppMessage() {
        return {};
    },
    switchTreat() {
        wx.navigateTo({url: '/pages/Composition/Composition'});
    },
    onLoad(options) {
        const that = this;
        if (Object.keys(options).length) {
            util.request(api.ReceiptDetail, {id: options.id}, 'get').then(function (res) {
                if (res.errno === 200) {
                    const info = res.data;
                    that.setData({
                        id: options.id,
                        type: info.type.toString(),
                        content: info.content,
                        mobile: info.mobile,
                        bankAccount: info.bankAccount,
                        workUnit: info.workUnit,
                        dutyParagraph: info.dutyParagraph,
                        openBank: info.openBank,
                        address: info.address,
                        company: info.company,
                        postAddress: info.postAddress,
                        postName: info.postName,
                        postNumber: info.postNumber,
                        reasonNote: info.reasonNote,
                        matter: info.reasonDesc,
                        reason: info.reason
                    });
                }
            });
        } else {
            that.setData({
                id: ''
            })
        }
        const {Reason} = app.globalData.enums;
        this.setData({
            reasonMap: Reason,
            reasons: Object.keys(Reason),
        })
    },
    submit(){
        const {
            content, type, bankAccount, openBank, address, mobile, dutyParagraph, company, id
            , postName, postNumber, postAddress, reasonNote, reason
        } = this.data;
        let infoCreate = {};
        if (type == 0) {// 普通发票
            infoCreate = {
               id, type, company, dutyParagraph,content,reason, reasonNote, postName, postNumber, postAddress
            }
        } else { // 增值税发票
            infoCreate = {
                id, type, company,dutyParagraph, mobile,address, openBank, bankAccount,content,reason,reasonNote, postName, postNumber, postAddress
            }
        }
        let hasError = false
        let keys = Object.keys(infoCreate);
        for(let i =0; i< keys.length;i++){
            let message = this.validate(null,keys[i])
            if(message){
                hasError = true;
            }
        }
        if(hasError){
            wx.showToast({
                title: '字段填写不完整',
                icon: 'error',
                duration: 2000
            })
            return;
        }
        if(!id){// 新增
            delete infoCreate.id;
            this.requestApi(infoCreate);
        }else{// 编辑
            util.request(api.ReceiptModify, infoCreate, 'post')
                .then(res => {
                    if (res.errno === 200) {
                        wx.showModal({
                            content: '您的信息已提交，请耐心等待，注意查收！',
                            showCancel: false,//是否显示取消按钮
                            confirmText: "确定",//默认是“确定”
                            confirmColor: 'rgb(31, 103, 220)',//确定文字的颜色
                            success: function (res) {
                                if (res.confirm) {
                                    wx.navigateBack({
                                        delta: 1
                                    })
                                }
                            },
                        })
                    } else {
                        wx.showToast({
                            title: res.errmsg,
                            icon: 'error',
                            duration: 2000
                        })
                        wx.navigateTo({url: '/pages/ReceiptInfo/ReceiptInfo'});
                    }
                })
        }
    },
    requestApi(infoCreate) {
        util.request(api.ReceiptCreate, infoCreate, 'post')
            .then(res => {
                if (res.errno === 200) {
                    wx.showModal({
                        content: '您的信息已提交，请耐心等待，注意查收！',
                        showCancel: false,//是否显示取消按钮
                        confirmText: "确定",//默认是“确定”
                        confirmColor: 'rgb(31, 103, 220)',//确定文字的颜色
                        success: function (res) {
                            if (res.confirm) {
                                wx.navigateBack({
                                    delta: 1
                                })
                            }
                        },
                    })
                } else {
                    wx.showToast({
                        title: res.errmsg,//提示文字
                        duration: 2000,//显示时长
                        mask: true,//是否显示透明蒙层，防止触摸穿透，默认：false
                        icon: 'error', //图标，支持"success"、"loading"
                    })
                }
            })
    },
    // 发票类型
    onChange(e) {
        this.setData({
            type: e.detail,
            phoneError: '',
            phoneError2: '',
            remarksError: '',
            matter: "",
            content: '',
            reason: "",
            reasonNote: '',
            mobile: "",
            address: "",
            bankAccount: "",
            openBank: "",
        })
    },
    validate(e, objKey){
        let { key} = (e && e.target.dataset) || {}
        let curKey = objKey || key;
        if(!rules.hasOwnProperty(curKey))return ''
        let curVal = this.data[curKey];
        let message = '';
        if(!curVal){
            this.setData({
                [curKey+'Error']: rules[curKey]+ '不可为空',
            })
            message = rules[curKey]+ '不可为空';
        }else{
            this.setData({
                [curKey+'Error']: '',
            })
            message=''
        }
        switch (objKey) {
            case 'reasonNote':
                if(this.data.reason==9&&!curVal){
                    message = '备注不可为空'
                }else{
                    message = ''
                }
                break;
            case 'postNumber':
                message = check.isValidPhone(curVal)
                this.setData({
                    postNumberError: message
                })
                break
            case 'mobile':
                message = check.isValidPhone(curVal)
                this.setData({
                    mobileError: message
                })
                break;
        }
        return message;
    }
});
